package EGS.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;

import javax.swing.JTable;

import org.dom4j.Document;
import org.dom4j.Element;

import com.google.gson.Gson;

import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import WORKPLACE.URLapi;
import WORKPLACE.m_panelSonResultState;
import WORKPLACE.stationClient;

public class EGS_execute_service5503Impl{
	public boolean isUnknowCase = false;
	ExecutorService iExecutorService;
	Document MSG;
	boolean isPanel = false;
	stationClient iClient=null;
	SQLtool sql = null;
	/**
	 * 5503 过站履历登记
	 */
	public EGS_execute_service5503Impl(stationClient nClient, Document MSG_in, ExecutorService executorService, 
			SQLtool goldenSql) throws Exception {
		super();
		sql=goldenSql;
		if(nClient!=null) {
			iClient=nClient;
		}else {
			iClient=null;
		}
		MSG = MSG_in;
		iExecutorService = executorService;
	}
	
	public Document runCal() {
		if (MSG == null) {
			return null;
		}
		Element Mroot = MSG.getRootElement();
		Element eleR = Mroot.element("body").addElement("result");
		try {
//			String transactionID = Mroot.element("header").attribute("transactionID").getValue();
//			eleR.addAttribute("actionCode", transactionID);//部分设备需要 <result errorCode=
			String iStation = Mroot.element("header").element("location").attribute("equipmentName").getValue();
			if(iClient==null) {
				throw new Exception("工位信息获取失败");
			}
			String msgClass = Mroot.element("header").attribute("messageClass").getValue();
			if (!(msgClass.equals("5503"))) {
				throw new Exception("实现类用错:"+this.getClass().getName());
			}
			List<?> panels =Mroot.element("body").elements("panel");
			if(panels!=null && panels.size()>0) {
				for(int i=0;i<panels.size();i++) {
					calBody((Element) panels.get(i),iStation,msgClass);
					Mroot.element("body").remove((Element)panels.get(i));
				}
			}

			eleR.addAttribute("errorCode", "0");
			eleR.addAttribute("errorText", "");
			try {
				URLapi aa=new URLapi();
				aa.RESTInvoker("http://192.168.0.220:8081", "","");
				StationAddress poster=new StationAddress();
				poster.ipAddress=iStation;
				poster.state="0";//将550作为无板监控
				String ijson=new Gson().toJson(poster);
				aa.postDataToServer("/api/alarm/smtState", ijson);
			} catch (Exception e) {
				AKSLogs(250604,"5503("+iStation+")无板监控异常："+e.getMessage());
			}
		} catch (Exception e) {
			String str = errCodeManagement.getErrText(e.getMessage());
			System.out.println(str);
			eleR.addAttribute("errorCode", "1");
			eleR.addAttribute("errorText", str);
		}

		return MSG;
	}
	
	public void calBody(Element panel,String iStation, String msgClass) throws Exception {
		String iSN, iLayer,iState;
		int iiLayer,iiState = 0;
		
		iSN = panel.attribute("pcbID").getValue();
		iLayer = panel.attribute("productSide").getValue();
		iState = panel.attribute("state").getValue();
		String iRepair = "0";
		try {
			iRepair = panel.attribute("repairType").getValue();
		} catch (Exception e) {
			iRepair = "0";
		}
		String procedure="-1";
		try {
			procedure = panel.attribute("procedureNumber").getValue();
			if(procedure.length()<1) {
				procedure="-1";
			}
		}catch(Exception ee) {
			procedure="-1";
		}
		if(procedure.equals("-1")) {
			procedure=iClient.myProcedureNumber;
		}
		List<?> sons = panel.elements();
		iiLayer = Integer.parseInt(iLayer);
		
		boolean isget = false;
		try {
			iiState = Integer.parseInt(iState);
			isget = true;
		}catch(Exception e) {
			String str = errCodeManagement.getErrText("过站电文异常body->panel->state_"+e.getMessage());
			AKSLogs(55030, "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
			throw new Exception(str);
		}
//		endT = GetTimestamp();
//		diffMS = getDiffMS(startT1, endT);
		if(isget && (iiLayer==-1)) {
			iiLayer=iClient.myLayer;
		}
		if (!isget) {
			;
		} else if (iiLayer != iClient.myLayer) {
			String str = "工单激活面别(" + iClient.myLayer + ")与产品上传面别不一致！";
			AKSLogs(55030, "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
			throw new Exception(str);
		} else {
			boolean bState = false;
			if (iiState == 0) {
				bState = true;
			}
			boolean bRepair = false;
			if (iRepair.equals("1")) {
				bRepair = true;
			}
			try {
				boolean icallXRay = false;
				if ((!iClient.isPanel)) {//5503为了适配德律AOI v3版软件
					throw new Exception("当前版本只能生产拼板工单");
				} else {
					m_panelSonResultState[] sonsState = new m_panelSonResultState[sons.size()];
					boolean gResult = true;

					for (int jj = 0; jj < sonsState.length; jj++) {
						if (((Element) (sons.get(jj))).getName().equals("subPanel")) {
							String iPos = ((Element) (sons.get(jj))).attribute("pos").getValue();
							String iResult = ((Element) (sons.get(jj))).attribute("state").getValue();// 0=无异常
							List<?> errComps = ((Element) sons.get(jj)).elements();
							
							sonsState[jj] = new m_panelSonResultState();//
							/**
							 * 	有复判的位号
							 */
							Vector<String> iRpComps =getRepairComps(errComps);//ss
							if (iRpComps.size() > 0) {// 判断是否加严清单中的案例
								Vector<String> iXRComps=getSPIxRayListComps(iPos);
								if (iXRComps.size() > 0) {
									for (int m = 0; m < iRpComps.size(); m++) {// 验证是否在加严清单中
										String strr = iRpComps.get(m);
										if (strr != null && strr.length() > 0) {
											if (iXRComps.indexOf(iRpComps.get(m)) >= 0) {
												icallXRay = true;
												sonsState[jj].callXRay = true;
												if(sonsState[jj].xRayComps.length()>0) {
													sonsState[jj].xRayComps=sonsState[jj].xRayComps+",";
												}
												sonsState[jj].xRayComps=sonsState[jj].xRayComps+iRpComps.get(m);
//												m = iRpComps.size() + 1;// 改成每一个加严清单中的位号都要可查询
											}
										}
									}
								}
							}
							sonsState[jj].pos = Integer.parseInt(iPos);
							sonsState[jj].isPass = false;
							if (iResult != null && iResult.equals("0")) {
								sonsState[jj].isPass = true;
								try {
									String iiRepair = ((Element) (sons.get(jj))).element("errComps")
											.attribute("comps").getValue();
									if (iiRepair != null && iiRepair.length() > 0) {
										sonsState[jj].isRepair = true;
									}
								} catch (Exception a) {
									;
								}
							} else {
								gResult = false;
								sonsState[jj]=getErrCompsInfo(sonsState[jj],errComps);
							}
							if(errComps!=null && errComps.size()>0) {
								iClient.uploadSubPanelResultData(iSN,iPos,errComps);
							}// 自动填充555
						} else {
							sonsState[jj] = new m_panelSonResultState();
						}
						
					}
					if(sons.size()==0) {
						iClient.uploadPanelState(iSN, gResult, bRepair, icallXRay,procedure);
					}else {
						
						if (procedure.equals("A0020") 
//								|| sCl.myProcedureNumber.equals("A0030")
								|| procedure.equals("A0040")) {
							iClient.uploadPanelState(iSN, gResult, bRepair, icallXRay,procedure);
						} else {
//							if(!gResult) {
//								AKSLogs(230810, "" +gXML);
//							}
							iClient.uploadPanelState(iSN, sonsState,procedure);
						}
					}
					
				}
				AKSLogs(55031, "" + iSN + "_" + iStation + "_" + iLayer);
			} catch (Exception e) {
				String str = errCodeManagement.getErrText(e.getMessage());
				AKSLogs(55030, "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
				throw new Exception(str);
			}
		}
			

	}

	public void AKSLogs(int iType, String ilogClientNews) {
		SQLtool.AKSLogs(iType, ilogClientNews);
	}
	
	private m_panelSonResultState getErrCompsInfo(m_panelSonResultState iState, List<?> errComps) {
		if(errComps==null || errComps.size()<1) {
			return iState;
		}
		iState.errComps=new String[errComps.size()];
		iState.errCode=new String[errComps.size()];
		for (int n = 0; n < errComps.size(); n++) {
			String isnRpass = "0";
			try {
				isnRpass = ((Element) errComps.get(n)).attribute("bRpass").getValue();
			}catch(Exception e) {
				isnRpass = ((Element) errComps.get(n)).attribute("Rpass").getValue();
			}
			if (isnRpass.equals("0")) {// 240509 改为0的按照不良品获取 
				iState.errComps[n]=((Element) errComps.get(n)).attribute("comps").getValue();
				iState.errCode[n]=((Element) errComps.get(n)).attribute("errCode").getValue();
			}
			
		}
		return iState;
	}
	
	/**
	 * 	获取在加严清单中的位号
	 * @param iPos 
	 * @param t
	 * @return
	 * @throws Exception 
	 */
	private Vector<String> getSPIxRayListComps(String iPos) throws Exception {

		Vector<String> iXRComps = new Vector<String>();
		String iMasterNumber = null;
		iMasterNumber=sql.selectFirstValue(
				"select masterNumber from vOrderListPanel where sequence=" + iPos
						+ " and panelOrderNumber='" + iClient.activeOrderNumber + "'");
		if (iMasterNumber != null && iMasterNumber.length() > 0) {// 查询总成号
			JTable t = sql.select(
					"select partNumber,comps,materialNumber from SPIxRayList where partNumber='"
							+ iMasterNumber + "'");
			if (t != null && t.getRowCount() > 0) {// 下载加严清单中该总成的所有位号
				for (int m = 0; m < t.getRowCount(); m++) {
					String strXR = "" + t.getValueAt(m, 1);
					if (strXR != null && strXR.length() > 0
							&& (!strXR.equals("null"))) {
						iXRComps.addAll(Arrays.asList(strXR.split(",")));
					}
				}
				
			}

		}
		
		return iXRComps;
	}

	/**
	 * 	获取有复判的位号
	 * @param errComps
	 * @return
	 */
	private Vector<String> getRepairComps(List<?> errComps) {
		Vector<String> iRpComps = new Vector<String>();
		for (int n = 0; n < errComps.size(); n++) {
			String isnRpass = "0";
			try {
				isnRpass = ((Element) errComps.get(n)).attribute("bRpass").getValue();
			}catch(Exception e) {
				isnRpass = ((Element) errComps.get(n)).attribute("Rpass").getValue();
			}
			if (isnRpass.equals("1")) {//231201 从0改为1，SPI中，1代表RPASS
				String[] strComps = ((Element) errComps.get(n)).attribute("comps")
						.getValue().split(",");
				iRpComps.addAll(Arrays.asList(strComps));
			}
		}
		return iRpComps;
	}

}
